<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryinfo.query"
            clearable
            @clear="gitUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="gitUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogvisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格 -->

      <el-table :data="userlist" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserByid(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加按钮的对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogvisible"
        width="50%"
        @close="addDialogclosed"
      >
        <!-- 内容主题区域 -->
        <el-form
          :model="addform"
          :rules="addformRules"
          ref="addformRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username"
            ><el-input v-model="addform.username"></el-input
          ></el-form-item>
          <el-form-item label="密码" prop="password"
            ><el-input v-model="addform.password"></el-input
          ></el-form-item>
          <el-form-item label="邮箱" prop="email"
            ><el-input v-model="addform.email"></el-input
          ></el-form-item>
          <el-form-item label="电话" prop="mobile"
            ><el-input v-model="addform.mobile"></el-input
          ></el-form-item>
        </el-form>
        <!-- 内容底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogvisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑表单得对话框 -->
      <el-dialog
        title="修改内容"
        :visible.sync="editdialogVisible"
        width="50%"
        @close="addDialogclosed">
        <!-- 文字信息 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
            <el-form-item label="用户名" prop="username" >
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>

    <!-- 分配角色的对话框 -->
    <el-dialog
     title="分配角色"
     :visible.sync="setRolesdialogVisible"
     width="50%" @close="setRoleDialogClosed">
     
     <p>当前的用户：{{userInfo.username}}</p>
     <p>当前的角色：{{userInfo.role_name}}</p>
     <p>分配新角色：
       <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
     </p>
     <span slot="footer" class="dialog-footer">
    <el-button @click="setRolesdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取用户的参数对象
      queryinfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      // 控制对话框的显示与颖仓
      addDialogvisible: false,
      // 添加用户的表单数据
      addform: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加表单的验证规则对象
      addformRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 11, max: 11, message: "长度在 11", trigger: "blur" },
        ],
      },
      // 控制编辑的弹出框的显示和隐藏
      editdialogVisible: false,
      // 查询回来的参数
      editForm:{},
      // 编辑表单的正则
      editFormRules:{
        
        email:[
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile:[
             { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 11, max: 11, message: '长度在 11 字符', trigger: 'blur' }
        ],
      },
      // 控制分配角色的对话框的显示喝隐藏
      setRolesdialogVisible:false,
      // 需要被分配角色的用户信息
      userInfo:{},
      // 所有角色的数据列表
      rolesList:[],
      // 已选中的id选中值
      selectedRoleId:''
    };
  },
  created() {
    this.gitUserList();
  },
  mounted() {},
  methods: {
    //   获取用户列表
    async gitUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryinfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");

      this.userlist = res.data.users;
      this.total = res.data.total;
      console.log(res);
    },
    // 监听 pagesize 改变的事件 每页显示多少条数据
    handleSizeChange(newsize) {
      // console.log(newsize);
      this.queryinfo.pagesize = newsize;
      // 获取新的数据
      this.gitUserList();
    },
    // 监听页码值改变
    handleCurrentChange(newpage) {
      // console.log(newpage);
      this.queryinfo.pagenum = newpage;
      this.gitUserList();
    },
    // 监听状态开关
    async userStatChanged(userinfo) {
      console.log(userinfo);
      // 发送请求
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("改变状态失败");
      }
      this.$message.success("改变状态成功");
      console.log(res);
    },
    // 监听对话框的关闭事件
    addDialogclosed() {
      this.$refs.addformRef.resetFields();
    },
    // 监听确定按钮提交对话表单
    addUser() {
      // 进行表单的校验
      this.$refs.addformRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        // 可以发起添加用户的请求
        const { data: res } = await this.$http.post("users", this.addform);

        if (res.meta.status !== 201) return this.$message.error("添加用户失败");

        this.$message.success("添加用户成功");
        // 关闭对话框
        this.addDialogvisible = false;
      });
    },
    // 编辑表单
    async showEditDialog(id) {
      this.editdialogVisible = true;
      // 获取表单信息
    const {data:res} = await this.$http.get('users/' + id)
    if(res.meta.status !== 200) {
      return this.$message.error('查询表单失败')
    }
    this.editForm = res.data
    this.$message.success('查询表单成功')
    console.log(this.editForm);
    },
    // 修改表单的重置
    addDialogclosed() {
        this.$refs.editFormRef.resetFields();
    },
    // 修改表单的提交
    editUserInfo() {
      // 先校验表单是否通过正则
      this.$refs.editFormRef.validate(async (valid) => {
        if(!valid) return
        // 验证通过 发送请求
        const {data:res} = await this.$http.put('users/' + this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
        })
        if(res.meta.status !== 200) {
          return this.$message.error('更新表单失败')
        }
        this.$message.success('更新表单成功')
        // 重新渲染表单
        this.gitUserList()
        this.editdialogVisible = false

      });
    },
    // 根据id删除对应的用户信息
    async removeUserByid(id) {
      console.log(id);
      // 弹框询问是否删除
       const abc = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)


        console.log(abc);
        if(abc !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        console.log('确认了删除');

        const {data:res} = await this.$http.delete('users/' + id)
        if(res.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        }
        this.$message.success('删除用户成功')
        // 代码优化
        if(this.total % this.queryinfo.pagesize === 1) {
          this.queryInfo.pagenum--
        }


        // 重新渲染页面
        this.gitUserList()


    },
    // 展示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo

      // 在展示对话框获取角色列表
      const {data:res} = await this.$http.get('roles')
      if(res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.$message.success('获取角色列表成功')
      this.rolesList = res.data

      this.setRolesdialogVisible = true
    },
    // 点击按钮分配角色
    async saveRoleInfo() {
      if(!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId})
      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('更新角色成功')
      // 重新渲染页面
      this.gitUserList()
      this.setRolesdialogVisible = false
    },
    // 监听分配角色的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = '',
      this.userInfo = {}
    }
  },
};
</script>

<style scoped lang="less">
</style>
